<?php

namespace app\common\command\task;

use app\common\service\FileLockService;
use think\facade\Db;

/**
 *
 * php think cron executeSql
 */
class ExecuteSql
{
    /**
     * invoke
     * @throws
     */
    public function invoke()
    {
        // 检查时间
        $hour = date('H');
        if ($hour != 3) {
            // return;
        }

        // 查询待执行的SQL
        $where = [['status', '=', 1]];
        $list = Db::table('think_execute_sql')->where($where)->select();

        // 循环执行SQL
        foreach ($list as $item) {
            $this->execute($item);
        }
    }

    /**
     * execute
     * @param $item
     * @throws
     */
    private function execute($item)
    {
        // 提取参数
        $id = $item['id'];

        // 加锁执行
        $lockKey = md5(__CLASS__ . $id);
        $lockService = new FileLockService($lockKey);
        $lockService->lockToExecute(function () use ($item) {
            // 记录执行结果
            $saveData = [
                'status' => 2,
                'update_time' => time(),
            ];

            // 执行SQL
            try {
                Db::query($item['sql']);
            } catch (\Exception $exception) {
                $saveData['status'] = 3;
                $saveData['error'] = $exception->getMessage();
            }

            // 保存结果
            $where = [['id', '=', $item['id']]];
            Db::table('think_execute_sql')->where($where)->update($saveData);
        }, false);
    }
}